package cmd

import (
	"context"
	"strings"

	"advertising/config/mysql"
	"advertising/internal/models"

	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"github.com/spf13/cobra"
)

// 修复数据的类型
var fixDataType string

func init() {
	rootCmd.PersistentFlags().StringVarP(&fixDataType, "type", "t", "", "fix db data")
	rootCmd.AddCommand(fixDBDataCmd)
}

// 数据库数据临时修复脚本
var fixDBDataCmd = &cobra.Command{
	Use:   "fixdb",
	Short: "fixdb",
	Run: func(*cobra.Command, []string) {
		switch fixDataType {
		case "materialmd5":
			var MaterialList = []models.Material{}
			mysql.NewDB().Model(&models.Material{}).
				Where("check_md5 = '' and deleted_at = 0").
				Find(&MaterialList)
			for _, material := range MaterialList {
				fullFilePath := ""
				if strings.HasPrefix(material.FilePath, "/Image") {
					fullFilePath = "/file/sale-admin" + material.FilePath
				} else {
					fullFilePath = material.FilePath
				}
				logx.Info(context.Background(), "material md5", logx.Any("material_id", material.ID), logx.Any("file_path", fullFilePath))
				md5 := helper.Md5File(fullFilePath)
				if md5 != "" {
					mysql.NewDB().Model(&models.Material{}).
						Where("id = ?", material.ID).
						Update("check_md5", md5)
				}
			}
		}
	},
}
